// cn/practice/listener/StudentReadListener.java

package cn.practice.listener;

import cn.practice.entity.Student;
import com.alibaba.excel.context.AnalysisContext;
import com.alibaba.excel.read.listener.ReadListener;
import lombok.Data;

import java.util.ArrayList;
import java.util.List;
import java.util.function.Consumer;

@Data
public class StudentReadListener implements ReadListener<Student> {

    private final List<Student> buffer = new ArrayList<>();
    private final List<ImportError> errorList = new ArrayList<>();
    private final int batchSize;
    private final Consumer<List<Student>> saveBatchConsumer;
    private final int[] total; // 总行数统计

    public StudentReadListener(int batchSize, Consumer<List<Student>> saveBatchConsumer, int[] total) {
        this.batchSize = batchSize;
        this.saveBatchConsumer = saveBatchConsumer;
        this.total = total;
    }

    @Override
    public void invoke(Student data, AnalysisContext context) {
        total[0]++; // 统计总行数
        int rowIndex = context.readRowHolder().getRowIndex() + 1;
        List<String> errors = validate(data);

        if (errors.isEmpty()) {
            buffer.add(data);
            if (buffer.size() >= batchSize) {
                saveBatchConsumer.accept(new ArrayList<>(buffer));
                buffer.clear();
            }
        } else {
            errorList.add(new ImportError(rowIndex, data, errors));
        }
    }

    @Override
    public void doAfterAllAnalysed(AnalysisContext context) {
        if (!buffer.isEmpty()) {
            saveBatchConsumer.accept(new ArrayList<>(buffer));
            buffer.clear();
        }
    }

    private List<String> validate(Student student) {
        List<String> errors = new ArrayList<>();
//        if (student.getName() == null || student.getName().trim().isEmpty()) {
//            errors.add("姓名不能为空");
//        }
        if (student.getAge() == null || student.getAge() < 0 || student.getAge() > 150) {
            errors.add("年龄必须在 0-150 之间");
        }
        return errors;
    }

    @Data
    public static class ImportError {
        private final int rowIndex;
        private final Student data;
        private final List<String> errors;
    }
}